package com.changwu.cwbase.net;


import com.blankj.utilcode.util.ToastUtils;
import com.changwu.cwbase.util.AppDialogUtil;

import org.json.JSONException;

import java.io.EOFException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by necer on 2017/6/28.
 */

public abstract class RxObserver<T> implements Observer<T> {


    private RxManager mRxManager;
    private int mWhichRequest;
    private String mKey;


    public RxObserver(String key, int whichRequest) {
        this.mKey = key;
        this.mWhichRequest = whichRequest;
        mRxManager = RxManager.getInstance();
    }


    @Override
    public final void onSubscribe(Disposable d) {
        mRxManager.add(mKey, d);
        onStart(mWhichRequest);
    }

    @Override
    public final void onNext(T value) {
        success(value);
    }

    @Override
    public final void onError(Throwable e) {
        AppDialogUtil.dismissProgressDialog();
        failure(e);
        if (e instanceof EOFException || e instanceof ConnectException || e instanceof SocketException || e instanceof BindException || e instanceof SocketTimeoutException || e instanceof UnknownHostException) {
            ToastUtils.showShort("网络异常，请稍后重试！");
        } else if (e instanceof JSONException) {
            ToastUtils.showShort("数据异常！");
        } else {
            ToastUtils.showShort("未知错误！");
        }
    }

    @Override
    public final void onComplete() {
        AppDialogUtil.dismissProgressDialog();
    }

    public abstract void success(T t);

    public void failure(Throwable e) {
    }

    ;

    public void onStart(int whichRequest) {

    }

}